
#include "stdafx.h"
#include "picbox.h"
#include "toolbox.hpp"
#include "global.h"
#include "resource.h"

PicBox::PicBox(void)
	: ImageCtrlBox()
	, m_contentheight(0)
{
}

PicBox::~PicBox(void)
{
}

void PicBox::Load(const WCHAR* path)
{
	std::list<std::wstring> subpaths;
	Toolbox::ListDirW(subpaths, path);
	for (std::list<std::wstring>::iterator it = subpaths.begin(); it != subpaths.end(); ++it)
	{
		WCHAR extname[8];
		Toolbox::SplitPathW(NULL, 0, NULL, 0, NULL, 0, extname, sizeof(extname)/sizeof(extname[0]), (*it).c_str());
		if (wcsnicmp(extname, L"jpg", sizeof(extname)/sizeof(extname[0])) != 0 &&
			wcsnicmp(extname, L"png", sizeof(extname)/sizeof(extname[0])) != 0)
		{
			continue;
		}
		if ((*it).find(L"%Thumb%") != std::wstring::npos)
		{
			continue;
		}

		PicCtrl* picctrl = new PicCtrl();
		picctrl->Load((*it).c_str());
		picctrl->SetButtonImage(&m_savectrl, &m_usectrl);
		m_imagectrls.push_back(picctrl);
	}

	ImageCtrl::ResInfo resinfo;
	resinfo = ImageCtrl::ResInfo::MakeResInfo(IDB_SAVE, RT_BITMAP, CXIMAGE_FORMAT_BMP);
	m_savectrl.Load(&resinfo, NULL, NULL);
	resinfo = ImageCtrl::ResInfo::MakeResInfo(IDB_USE, RT_BITMAP, CXIMAGE_FORMAT_BMP);
	m_usectrl.Load(&resinfo, NULL, NULL);

	Layout();
}

void PicBox::UnLoad()
{
	for (std::list<ImageCtrl*>::iterator it = m_imagectrls.begin(); it != m_imagectrls.end(); ++it)
	{
		delete *it;
		*it = NULL;
	}

	ImageCtrlBox::UnLoad();
}

long PicBox::GetContentHeight()
{
	size_t count_per_line = (m_rect.right - m_rect.left - THUMBNAIL_MARGIN_WIDTH) / THUMBNAIL_WIDTH;
	if (count_per_line == 0)
		count_per_line = 1;
	return ((m_imagectrls.size()+count_per_line-1) / count_per_line) * (THUMBNAIL_HEIGHT + THUMBNAIL_MARGIN_HEIGHT);
}

void PicBox::Layout()
{
	RECT rect = m_rect;
	rect.top -= m_posy;
	for (std::list<ImageCtrl*>::iterator it = m_imagectrls.begin(); it != m_imagectrls.end(); ++it)
	{
		ImageCtrl* imagectrl = *it;
		if (imagectrl != NULL)
		{
			rect.right = rect.left + THUMBNAIL_WIDTH;
			rect.bottom = rect.top + THUMBNAIL_HEIGHT;
			imagectrl->SetRect(rect);

			rect.left += THUMBNAIL_WIDTH + THUMBNAIL_MARGIN_WIDTH;
			if (rect.left + THUMBNAIL_WIDTH > m_rect.right)
			{
				rect.top += THUMBNAIL_HEIGHT + THUMBNAIL_MARGIN_HEIGHT;
				rect.left = m_rect.left;
			}
		}
	}
}
